'use strict';

var async = require('async');
var moment = require('moment');
var _ = require('lodash');
var mgrUtil = require('../util/mgrUtil');
var actType = require('../consts/activityType.js');
var eventType = require('../consts/eventType.js');
var playerManager = require('../libs/playerManager.js');
var configUtil = require('../util/configUtil');
var activityConf = require('../config/activityConf');
var buildType = require('../consts/buildType');
var dataApi = require('../libs/dataApi');
var constantUtil = require('../util/constantUtil');

exports.synchronization = function (player_manager, cb) {
    async.waterfall([
            function (cb) {
                var role_model = player_manager.role;
                var daily_task_model = player_manager.daily_task;
                var task_model = player_manager.task;
                var achieve_model = player_manager.achieve;

                // 同步主线任务操作
                _tackleTask(task_model);

                // 同步成就操作
                _tackleAchieve(achieve_model);
                cb();

            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return cb(null, err);
            }
            cb();
        }
    );
};

// 处理------主线任务
var _tackleTask = function (task_model) {
    // 同步主线任务
    var miss_id_conf_list = [];
    dataApi.mission.each(function (value, key) {
        miss_id_conf_list.push(+key);
    });

    var now_task_list = task_model.current_task_list;
    var not_key_list = [];
    _.each(now_task_list, function (now_task_key) {
        if (_.indexOf(miss_id_conf_list, now_task_key) == -1) {
            not_key_list.push(now_task_key);
        }
    });

    // 移除任务
    if (not_key_list.length > 0) {
        _.each(not_key_list, function (task_id) {
            task_model.removeTask(task_id);
        });
    }
};

// 处理------成就任务
var _tackleAchieve = function (achieve_model) {
    var achieve_id_conf_list = [];
    var now_achieve_list = achieve_model.current_task_list;
    dataApi.achieve.each(function (value, key) {
        achieve_id_conf_list.push(+key);
    });

    var remove_list = [];
    _.each(now_achieve_list, function (achieve_id) {
        if (_.indexOf(achieve_id_conf_list, achieve_id) == -1) {
            remove_list.push(achieve_id);
        }
    });

    // 移除任务
    if (remove_list.length > 0) {
        _.each(remove_list, function (achieve_id1) {
            achieve_model.removeTask(achieve_id1);
        });
    }
};
